<template>
  <div class="box">
    <header class="header">
      <van-nav-bar
        title="选择地址"
        left-arrow
        @click-left="$router.back()"
      />
    </header>
    <div class="content">
      <van-address-edit
        :area-list="areaList"
        show-set-default
        save-button-text="保存并使用"
        :area-columns-placeholder="['请选择', '请选择', '请选择']"
        @save="onSave"
      />
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { NavBar, AddressEdit, Toast } from 'vant'
import areaList from '@/utils/area'
import { addressAdd, updateOrderAddress } from '@/api/address'
import { mapState } from 'vuex'
Vue.use(NavBar)
Vue.use(AddressEdit)
export default {
  data () {
    return {
      areaList: areaList
    }
  },
  computed: {
    ...mapState({
      userid: ({ user: { userid } }) => userid
    })
  },
  methods: {
    formatAddress (province, city, county) {
      let str = ''
      str = province === city ? province + county : province + city + county
      return str
    },
    onSave (content) {
      content.userid = this.userid
      addressAdd(content).then(() => {
        Toast('保存地址成功')
        updateOrderAddress({
          userid: content.userid,
          time: this.$route.params.time,
          name: content.name,
          tel: content.tel,
          address: this.formatAddress(content.province, content.city, content.county) + ' ' + content.addressDetail
        }).then(() => {
          this.$router.go(-2)
        })
      })
    }
  }
}
</script>
